import axios from "axios"
import modal from '@/plugins/modal'

//文件下载:请求地址,文件夹,文件路径,文件名
export const downloadFile = async (url, fileName) => {
    //// 将下载地址借助 Blob转为二进制,然后使用a标签进行下载
    // 1.fetch实现
    // const link = document.createElement("a");
    // fetch(url)
    //   .then((res) => res.blob())
    //   .then((blob) => {
    //     // 将链接地址字符内容转变成blob地址
    //     link.href = window.URL.createObjectURL(blob);
    //     link.download = fileName;
    //     link.style.display = "none";
    //     document.body.appendChild(link);
    //     link.click();
    //     document.body.removeChild(link);
    //   });
    //2.axios实现
    try {
        const response = await axios.get(url, { responseType: "blob" });
        const contentType = response.headers["content-type"];
        const blob = new Blob([response.data], { type: contentType });
        if (typeof window.navigator.msSaveBlob !== "undefined") {
            // 兼容IE浏览器
            window.navigator.msSaveBlob(blob, fileName);
        } else {
            const link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.style.display = "none";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        }
        return true
    } catch (err) {
        return err
    }
}

//将图片转为Base64
export const getBase64 = (rawFile) => {
    return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(rawFile);
        reader.onload = function () {
            imgResult = reader.result;
        };
        reader.onerror = function (error) {
            reject(error);
        };
        reader.onloadend = function () {
            resolve(imgResult);
        };
    });
}